package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.item.vo.CategoryView;
import com.atguigu.gmall.product.entity.BaseCategory1;
import com.atguigu.gmall.product.mapper.BaseCategory1Mapper;
import com.atguigu.gmall.product.service.BaseCategory1Service;
import com.atguigu.gmall.weball.CategoryVO;
import com.atguigu.mall.cache.annotation.MallCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.map.HashedMap;
import org.jooq.tools.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author lfy
 * @Description
 * @create 2022-10-29 14:39
 */
@Service
public class BaseCategory1ServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1>
        implements BaseCategory1Service {

    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @MallCache(cacheKEY = RedisConst.CATEGORY_CACHE_KEY)
    @Override
    public List<CategoryVO> getCategoryTreeData() {
        return baseCategory1Mapper.getCategoryTreeData();
    }


    //本地缓存 吞吐量4000多
    Map<String,List<CategoryVO>> cache = new ConcurrentHashMap<>();

    //@MallCache-----categorys

    public List<CategoryVO> getCategoryTreeDataWithCache(){
        //1,查询缓存
        String categorys = redisTemplate.opsForValue().get("categorys");
        if (!StringUtils.isEmpty(categorys)){
            //2,缓存命中
            List<CategoryVO> vos = JSON.parseObject(categorys, new TypeReference<List<CategoryVO>>() {
            });
            return vos;
        }

        //3,缓存未命中
        List<CategoryVO> data = baseCategory1Mapper.getCategoryTreeData();
        //无论数据放不放缓存
        redisTemplate.opsForValue().set("categorys", JSON.toJSONString(data));
        return baseCategory1Mapper.getCategoryTreeData();

    }


    public List<CategoryVO> getCategoryTreeDataWithLocalCache() {
        //1，本地缓存
        List<CategoryVO> categorys = cache.get("categorys");
        if (categorys!=null){
            //2,缓存命中
            return categorys;
        }
        //3,缓存未命中，查询数据库-------也就是回源
        List<CategoryVO> vos = baseCategory1Mapper.getCategoryTreeData();

        //4,数据放到缓存，方便下一次查询
        cache.put("categorys", vos);
        return vos;
    }

    @Override
    public CategoryView getSkuCategoryView(Long c3Id) {
        return baseCategory1Mapper.getSkuCategoryView(c3Id);
    }
}
